package com.laomuji.android.mvvm.utils

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.view.View
import androidx.core.graphics.createBitmap

/**
 * View工具
 * @author laomuji666
 * @since 2024/2/21
 */
object ViewUtil {
    /**
     * 去掉Context的包装,有些情况下 Context会被包装未ContextWrapper
     */
    fun unwrapContext(contextVal: Context): Activity {
        var context = contextVal
        while (context !is Activity && context is ContextWrapper) {
            context = context.baseContext
        }
        return context as Activity
    }

    /**
     * View置灰色
     */
    fun saturationView(view: View, isGray: Boolean) {
        val colorMatrix = ColorMatrix()
        colorMatrix.setSaturation(if (isGray) 0f else 0.5f)
        val paint = Paint()
        paint.setColorFilter(ColorMatrixColorFilter(colorMatrix))
        view.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
    }

    /**
     * 不建议频繁使用,在内存小的机器上多次使用可能会导致手机没有内存
     */
    fun getViewBitmap(v: View): Bitmap {
        return try {
            val bitmap = createBitmap(v.width, v.height)
            val canvas = Canvas(bitmap)
            v.draw(canvas)
            bitmap
        } catch (e: Exception) {
            createBitmap(200, 200, Bitmap.Config.ARGB_4444)
        }
    }
}